<template>
  <u-popup :closeOnClickOverlay="false" :closeable="true" :round="10" :show="show" bgColor="#fff" zIndex="10081"
    @close="handleClose">
    <view v-if="payInfo" class="flex flex-col h-[70vh] popup-common" @touchmove.prevent.stop>
      <view class="head">
        <view class="title">
          {{ t('pay.payTitle') }}
        </view>
        <view class="flex items-end justify-center w-full text-xl font-bold py-[20rpx] price-font">
          <view class="text-base mr-[4rpx]">{{ t('currency') }}</view>
          {{ moneyFormat(fen2yuan(payInfo.price)) }}
        </view>
      </view>
      <scroll-view class="flex-1  pt-[20rpx]" scroll-y="true">
        <view class="flex text-[32rpx] px-[36rpx] py-[20rpx] mb-[10rpx]">
          <view class="text-[var(--text-color-light6)]">{{ t('pay.orderInfo') }}</view>
          <view class="text-right flex-1 pl-[30rpx] truncate">{{ payInfo.body }}</view>
        </view>
        <view class="mx-[var(--popup-sidebar-m)] px-[30rpx] bg-white rounded-[20rpx] bg-[var(--temp-bg)]">
          <block v-if="payInfo.pay_type_list.length">
            <view v-for="(item, index) in payInfo.pay_type_list" :key="index"
              class="pay-item py-[30rpx] flex items-center border-0 border-b border-solid border-[#eee]"
              @click="type = item.key">
              <u-image :src="img(item.icon)" height="50rpx" width="50rpx"></u-image>
              <view class="flex-1 px-[20rpx] text-[32rpx] font-500">{{ item.name }}</view>
              <u-icon v-if="item.key == type" color="var(--primary-color)" name="checkbox-mark"></u-icon>
            </view>
          </block>
          <view v-else class="py-[30rpx] text-center text-[24rpx] text-gray-subtitle">{{
            t('pay.notHavePayType')
          }}
          </view>
        </view>
      </scroll-view>
      <view class="btn-wrap">
        <button :loading="loading" class="primary-btn-bg btn" hover-class="none" @click="confirmPay">
          {{ t('pay.confirmPay') }}
        </button>
      </view>
    </view>
  </u-popup>
  <!-- 合利宝付款码支付 -->
  <view @touchmove.prevent.stop>
    <u-popup class="popup-type" :show="authCodeShow" @close="authCodeShow = false" zIndex="10082">
      <view class="min-h-[360rpx] popup-common" @touchmove.prevent.stop>
        <view class="title">合利宝付款码支付</view>
        <scroll-view class="h-[520rpx]" scroll-y="true">
          <view class="bg-white flex items-center leading-[30rpx] px-[var(--pad-sidebar-m)]">
            <view class="text-[32rpx] w-[180rpx] text-[#303133]">支付条形码</view>
            <view class="flex-1 text-[#303133] flex  justify-end items-center">
              <input type="text" v-model="authCode" class="text-right text-[#333] text-[32rpx]" maxlength="50"
                placeholder="请输入支付条形码" placeholder-class="text-[var(--text-color-light9)] text-[32rpx]">
              <!--  #ifndef  H5 -->
              <u-icon name="scan" color="#999" size="28" @click="handelScan"></u-icon>
              <!-- #endif -->

            </view>
          </view>
        </scroll-view>
        <view class="btn-wrap">
          <button :loading="loading" class="primary-btn-bg btn" hover-class="none" @click="confirmPay">
            {{ t('pay.confirmPay') }}
          </button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { t } from '@/locale'
import { getPayInfo, pay, getEnableChannelCodeList } from '@/app/api/pay'
import { img, isWeixinBrowser, moneyFormat, redirect, currRoute } from '@/utils/common'

import wechat from '@/utils/wechat'
import { fen2yuan } from '@/utils/formatting'
// #ifdef H5
if (isWeixinBrowser()) wechat.init();
// #endif


const show = ref(false)
const loading = ref(false)
const authCodeShow = ref<boolean>(false) //付款码支付
const authCode = ref('')

const payInfo = ref<AnyObject | null>(null)
const type = ref('')
/**
 * 扫码支付
 */
const handelScan = () => {
  // 调起条码扫描
  uni.scanCode({
    scanType: ['barCode'],
    onlyFromCamera: true,
    success: function (res) {
      console.log('条码类型：' + res.scanType);
      console.log('条码内容：' + res.result);
      authCode.value = res.result
      confirmPay()
    }
  });
}
/**
 * 支付方式 默认先写死
 */
const payTypeList = ref([
  {
    key: "hlb_passive",
    icon: "https://meton-cloud-files.oss-cn-beijing.aliyuncs.com/aggregate-pay.png",
    name: "合利宝付款码支付",
    config: "{\"name\":\"\"}"
  },
  {
    key: "cash",
    icon: "https://meton-cloud-files.oss-cn-beijing.aliyuncs.com/cash-pay.png",
    name: "现金支付",
    config: "{\"name\":\"\"}"
  },
  {
    key: "wallet",
    icon: "static/resource/icon/pay_icon/balancepay.png",
    name: "余额支付",
    config: "{\"name\":\"\"}"
  }
])
/**
 * 合利宝
 * 检查支付状态
 */
uni.$on('scene', (e) => {
  if (e.scene == 1038) {
    checkPayStatus()
  }
})
const checkPayStatus = () => {
  if (!orderTradeId.value) {
    return
  }
  getPayInfo({ id: orderTradeId.value, sync: true }).then(async (res: any) => {

    let { data } = res
    // 设置支付状态
    if (data.status === 10 || data.status === 20) {
      show.value = false
      // 支付成功
      // 跳转回支付成功页
      uni.showModal({
        title: '提示',
        content: '订单已支付',
        showCancel: false,
        success: function () {
          toPayResult()

        },
      });
      return;
    }
  })
  orderTradeId.value = null

}

/**
 * 获取支付方式
 */

const setPayMethods = async () => {
  // let params = { appId: payInfo.value?.appId }
  // const res = await getEnableChannelCodeList(params);
  // payInfo.value!.pay_type_list = getPayMethods(res.data);
  payInfo.value!.pay_type_list = getPayMethods();

}

const getPayMethods = () => {
  // let payList = [] as any
  // if ((isWeixinBrowser() && channels.includes('wx_pub')) || (!isWeixinBrowser() && channels.includes('wx_lite'))) {
  //  payList.push(payTypeList.value[0])
  // }
  // if (channels.includes('hlb_pre')) {
  //  payList.push(payTypeList.value[1])
  // }
  // if (channels.includes('wallet')) {
  //    payList.push(payTypeList.value[2])
  // }
  if (orderTradeType.value == 'recharge') {
    payTypeList.value = [{
      key: "hlb_passive",
      icon: "https://meton-cloud-files.oss-cn-beijing.aliyuncs.com/aggregate-pay.png",
      name: "合利宝付款码支付",
      config: "{\"name\":\"\"}"
    },
    {
      key: "cash",
      icon: "https://meton-cloud-files.oss-cn-beijing.aliyuncs.com/cash-pay.png",
      name: "现金支付",
      config: "{\"name\":\"\"}"
    },]
  }

  return payTypeList.value
}
/**
 * 确认支付
 */
const confirmPay = () => {
  if (uni.$u.test.isEmpty(type.value)) {
    uni.showToast({ title: t('pay.notHavePayType'), icon: 'none' })
    return
  }
  if (type.value == 'hlb_passive' && !authCode.value) {
    // authCodeShow.value = true
    handelScan()
    return false
  }


  if (loading.value) return
  loading.value = true
  let data = {
    id: payInfo.value?.id,
    channelCode: type.value,
    channelExtras: {
      authCode: authCode.value
    },
  };
  if (!isWeixinBrowser() && type.value == 'wechat') {
    data.channelCode = 'wx_lite'
  } else if (isWeixinBrowser() && type.value == 'wechat') {
    data.channelCode = 'wx_pub'
  }


  pay(data).then((res: any) => {
    const payConfig = res.data.displayContent ? JSON.parse(res.data.displayContent) : {};

    switch (type.value) {
      case 'hlb_pre':
        // #ifndef H5
        uni.openEmbeddedMiniProgram({
          appId: payConfig.appId,
          path: payConfig.payPath,
          success: (res) => {
            // that.payResult('success');

          },
          fail: (err) => {
          },


        });
        // #endif

        break;

      case 'wechat':
        // #ifndef H5

        uni.requestPayment({
          provider: 'wxpay',
          timeStamp: payConfig.timeStamp,
          nonceStr: payConfig.nonceStr,
          package: payConfig.packageValue,
          signType: payConfig.signType,
          paySign: payConfig.paySign,
          success: (res: any) => {
            toPayResult()
          },
          fail: (res: any) => {
            loading.value = false
          }
        })
        // #endif
        // #ifdef H5
        if (isWeixinBrowser()) {
          res.data.timestamp = res.data.timeStamp
          delete res.data.timeStamp
          wechat.pay({
            ...res.data,
            success: () => {
              toPayResult()
            },
            cancel: () => {
              loading.value = false
            }
          })
        } else {
          uni.setStorageSync('paymenting', {
            trade_type: payInfo.value?.trade_type,
            trade_id: payInfo.value?.trade_id
          })
          location.href = res.data.h5_url
        }
        // #endif
        break;
      case 'alipay':
        // #ifdef H5
        if (isWeixinBrowser()) {
          redirect({
            url: '/app/pages/pay/browser',
            param: {
              trade_type: payInfo.value?.trade_type,
              trade_id: payInfo.value?.trade_id,
              alipay: encodeURIComponent(res.data.url)
            },
            mode: 'redirectTo'
          })
        } else {
          uni.setStorageSync('paymenting', {
            trade_type: payInfo.value?.trade_type,
            trade_id: payInfo.value?.trade_id
          })
          location.href = res.data.url
        }
        // #endif
        break;
      default:
        if (res.data.url) {
          redirect({
            url: res.data.url,
            param: res.data.param || {},
            mode: 'redirectTo'
          })
          return
        }
        toPayResult()
    }
  }).catch(() => {
    loading.value = false
  })
  authCodeShow.value = false
  authCode.value = ''
}

/**
 * 检测是否是支付后返回
 */
uni.$on('checkIsReturnAfterPayment', () => {
  const data = uni.getStorageSync('paymenting')
  if (uni.getStorageSync('paymenting')) {
    redirect({
      url: '/app/pages/pay/result',
      param: {
        trade_type: data.trade_type,
        trade_id: data.trade_id
      },
      mode: 'redirectTo',
      success() {
        uni.removeStorageSync('paymenting')
      }
    })
  }
})
const repeat = ref(false)
const orderTradeType = ref()
const orderTradeId = ref()
/**
 * 
 * @param tradeType  '交易类型'
 * @param tradeId '交易订单号'
 * @param payReturn 
 * @param scene '原代码逻辑暂时没用到'
 */
const open = (tradeType: string, tradeId: number, payReturn: string = '', scene: string = '') => {
  orderTradeType.value = tradeType
  orderTradeId.value = tradeId
  if (repeat.value) return
  repeat.value = true

  // 设置支付后跳转页面
  uni.setStorageSync('payReturn', encodeURIComponent(payReturn))

  // 帮人付款时过滤帮付选项
  const obj: any = {}
  if (scene) {
    obj.scene = scene
  }
  getPayInfo({ id: tradeId, sync: true }).then(async (res: any) => {

    let { data } = res
    data.pay_type_list = []
    payInfo.value = data
    // 设置支付状态
    if (payInfo.value.status === 10 || payInfo.value.status === 20) {
      show.value = false
      // 支付成功
      // 跳转回支付成功页
      uni.showModal({
        title: '提示',
        content: '订单已支付',
        showCancel: false,
        success: function () {
          toPayResult()

        },
      });
      return;
    }
    await setPayMethods()

    if (uni.$u.test.isEmpty(data)) {
      uni.showToast({ title: t('pay.notObtainedInfo'), icon: 'none' })
      return
    }
    if (data.price == 0) {
      toPayResult()
      return
    }
    type.value = payInfo.value.pay_type_list[0] ? payInfo.value.pay_type_list[0].key : ''

    show.value = true
    repeat.value = false

  }).catch(() => {
    repeat.value = false
  })
}
// 状态转换：payOrder.status => payStatus



const emits = defineEmits(['close', 'confirm'])
const toPayResult = () => {
  emits('confirm')
  redirect({
    url: '/app/pages/pay/result',
    param: { trade_type: orderTradeType.value, trade_id: payInfo.value?.id },
    mode: 'redirectTo'
  })
}


const handleClose = () => {
  uni.removeStorageSync('paymenting')
  show.value = false
  emits('close')
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.pay-item:last-child {
  border: none;
}
</style>
